<?php

// LVM
//@session_start();

class AdminFicheController extends ModuleAdminController {

	protected function storeSizeAllSubmit($modulator)
	{
		if ( isset($_POST['storeSizeAllSubmit']) && !empty($_POST['storeSizeAllSubmit']) )
		{
			$list = explode(',', $_POST['actionList']);
			$store = ceil((float)($_POST['storeSizeAll']) * $modulator);
			
			foreach( $list as $value )
			{
				$abo = FicheAbo::getFicheAbo((int)($value));
				
				if ( $abo != null )
				{
					$abo->storeSize = $store;
					$abo->update();
				}
			}
		}
	}

	protected function connectAsUser()
	{
		// LVM
		//@session_start();

		if ( isset($_GET['login']) && !empty($_GET['login']) && isset($_GET['id_customer']) )
		{
			$link = new Link();
			$linkModule = $link->getModuleLink('fichevitrine', 'default');
			
			//echo 'link1 = '.$linkModule.'---';
			
			if ( !isset($_SESSION) )
			{
				session_start();
				//echo 'ici895'.'---';
			}
			
			//var_dump($_SESSION);
			
			// LVM
			//session_register("authentification"); // enregistrement de la session
			
			// LVM : $_SESSION est effacée pendant le trajet... raison inconnue.
			//       Le comportement est aléatoire selon les jours, le navigateur, la météo, ...
			//       En fait le session_start doit être lancé avant tout code html...
					
			//$_SESSION['id_customer'] = (int)($_GET['id_customer']);
			//$_SESSION['adminKey'] = Configuration::get('fichevitrine_adminKey_');
			// setcookie('pays', 'France', time() + 365*24*3600, null, null, false, true); 
			
			//var_dump($_SESSION);
			
			//Context::getContext()->session = $_SESSION;
			//$this->context->smarty->assign(array(
			
			/*	
			Context::getContext()->smarty->assign(array(
			'id_customer2' => (int)($_GET['id_customer']),
			'adminKey2' => Configuration::get('fichevitrine_adminKey_') ));
			
			var_dump(Context::getContext()->smarty->getGlobal());
			*/
			
			// Paramétrage
			$cle_crypt = 'unjoursansfin1234';

			// Cryptage de la donnée
			$data_crypt = $this->f_crypt($cle_crypt, $_GET['id_customer']);
			
			//echo 'data_crypt = '.$data_crypt.'---';
			
			//exit;
			
			// LVM : le décryptage ne fonctionne pas toujours...
			/*
			// Clef de cryptage
			$cle_crypt = 'unjoursansfin1234';
			
			$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
			$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
			
			echo 'iv_size = '.$iv_size.'---';
			echo 'iv = '.$iv.'---';
			echo 'MCRYPT_RAND = '.MCRYPT_RAND.'---';
			
			// Data à crypter
			$data = (int)($_GET['id_customer']);
			
			echo 'data = '.$data.'---';
			
			// Cryptage
			$data_crypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $cle_crypt, $data, MCRYPT_MODE_ECB, $iv);
			$data_crypt_sans_caractere_speciaux = base64_encode($data_crypt);
			
			echo 'data_crypt = '.$data_crypt.'---';
			echo 'data_crypt_sans_caractere_speciaux = '.$data_crypt_sans_caractere_speciaux.'---';
					
			echo 'data_crypt_sans_caractere_speciaux urlencode = '.urlencode($data_crypt_sans_caractere_speciaux).'---';
			//echo 'data_crypt urlencode = '.urlencode($data_crypt).'---';
			//exit;
			
			//echo 'avant dump0 session'.'---';
			//var_dump($_SESSION);
			//exit;
			
			echo 'link2 = '.$linkModule.'?loginAsCustomer=1'.'---';
			//exit;
			
			// LVM test
			//Tools::redirect($linkModule.'?loginAsCustomer=1');
			//Tools::redirect($linkModule.'?loginAsCustomer=1&id_customer='.(int)($_GET['id_customer']));
			//Tools::redirect($linkModule.'?loginAsCustomer=1&id_customer='.urlencode($data_crypt_sans_caractere_speciaux));
			*/	
			Tools::redirect($linkModule.'?loginAsCustomer=1&id_customer='.urlencode($data_crypt));
			
			//Tools::redirect($linkModule.'?loginAsCustomer=1&id_customer='.(int)($_GET['id_customer']));		
		}
	}
	
	// LVM
	protected function f_crypt($private_key, $str_to_crypt) 
	{
		// LVM : pour que cela fonctionne à tous les coups on enlève le MD5
		//$private_key = md5($private_key);
		
		//echo 'md5 clef crypt = '.$private_key.'---';
		
		$letter = -1;
		$new_str = '';
		$strlen = strlen($str_to_crypt);

		for ($i = 0; $i < $strlen; $i++) 
		{
			$letter++;
			
			if ($letter > 31) 
			{
				$letter = 0;
			}
			
			$neword = ord($str_to_crypt{$i}) + ord($private_key{$letter});
			
			if ($neword > 255) 
			{
				$neword -= 256;
			}
			
			$new_str .= chr($neword);
		}
		
		return base64_encode($new_str);
	}
	
	// LVM : recherche user Prestashop (différent du user LFV)
	protected function searchUserBy()
	{
		$result = array();
		
		$sql = 'SELECT id_customer, firstname, lastname, email, company FROM '. _DB_PREFIX_ . 'customer';
		
		$i = 0;
		
		if ( isset($_POST['searchUser']) && !empty($_POST['searchUser']) )
		{
			if ( isset($_POST['company']) && !empty($_POST['company']) )
			{
				$sql .= ($i == 0)? ' WHERE' : ' AND';	$i++;
				
				// LVM : recherche en Like
				//$sql .= ' company = "'.$_POST['company'].'"';
				$sql .= ' company LIKE "%'.$_POST['company'].'%"';
			}
			
			if ( isset($_POST['firstname']) && !empty($_POST['firstname']) )
			{
				$sql .= ($i == 0)? ' WHERE' : ' AND';	$i++;
				
				// LVM : recherche en Like
				//$sql .= ' firstname = "'.$_POST['firstname'].'"';
				$sql .= ' firstname LIKE "%'.$_POST['firstname'].'%"';
			}
			
			if ( isset($_POST['lastname']) && !empty($_POST['lastname']) )
			{
				$sql .= ($i == 0)? ' WHERE' : ' AND';	$i++;
				
				// LVM : recherche en Like
				//$sql .= ' lastname = "'.$_POST['lastname'].'"';
				$sql .= ' lastname LIKE "%'.$_POST['lastname'].'%"';
			}
			
			// LVM : recherche par email
			if ( isset($_POST['email']) && !empty($_POST['email']) )
			{
				$sql .= ($i == 0)? ' WHERE' : ' AND';	$i++;
				
				// LVM : recherche en Like
				$sql .= ' email LIKE "%'.$_POST['email'].'%"';
			}

			$result = Db :: getInstance()->ExecuteS($sql);
		}
		
		return $result;
	}
	
	protected function createUser()
	{
		if ( isset($_POST['createUser']) && !empty($_POST['createUser']) )
		{
			$list = Customer::getCustomersByEmail($_POST['userEmail']);
			
			foreach( $list as $value )
			{
				FicheAbo::getFicheAbo((int)($value['id_customer']));
			}
		}
	}
	
	protected function saveConfig()
	{
		if ( isset($_POST['saveConfig']) && !empty($_POST['saveConfig']) )
		{
			Configuration::updateValue('fichevitrine_autoSaveTime_', (int)($_POST['autoSaveTime']));
			Configuration::updateValue('fichevitrine_autoSave_', (int)($_POST['autoSave']));
			Configuration::updateValue('fichevitrine_fontList_', $_POST['fontList']);
			Configuration::updateValue('fichevitrine_fontSizeStart_', (int)($_POST['startSize']));
			Configuration::updateValue('fichevitrine_fontSizeEnd_', (int)($_POST['endSize']));
		}
	}
	
	protected function addTheme()
	{
		if ( isset($_POST['addTheme']) && !empty($_POST['addTheme']) )
		{
			FicheTheme::addTheme($_POST['themeName']);
		}
	}
	
	protected function killTheme()
	{
		if ( isset($_POST['deleteTheme']) && !empty($_POST['deleteTheme']) )
		{
			FicheTheme::killThemeById((int)($_GET['id_theme']));
		}
		
	}
	
	protected function addProp()
	{
		if ( isset($_POST['addProp']) && !empty($_POST['addProp']) )
		{
			FicheProp::addProp($_POST['propName']);
		}
	}
	
	protected function killProp()
	{
		if ( isset($_POST['deleteProp']) && !empty($_POST['deleteProp']) )
		{
			FicheProp::killPropById((int)($_GET['id_prop']));
		}
		
	}
	
	protected function saveAbo($modulator)
	{
		if ( isset($_POST['saveAbo']) && !empty($_POST['saveAbo']) )
		{
			$abo = FicheAbo::getFicheAbo((int)($_POST['id_customer']));
			if ( $abo != null )
			{
				$abo->date_start = $_POST['date_start'];
				$abo->date_end = $_POST['date_end'];
				$abo->storeSize = ceil((float)($_POST['storeSize']) * $modulator);
				$abo->twoInOne = (int)($_POST['twoInOne']);
				$abo->update();
			}
		}
	}
	
	protected function getStats()
	{
		$results = array();
		$results['accounts'] = array();
		$results['fiches'] = array();
		
		$conditions = array();
		
		// LVM : voir ce qu'il y a dans le passé est plus utile...
		/*
		$date_start = date('Y-m-d 00:00:00', time());
		$date_end = date('Y-m-d H:i:s', time() + ( 24 * 365 * 60 * 60 ) );
		*/
		//$date_start1 = date('Y-m-d H:i:s', time() - ( 24 * 60 * 60 * 365 ) );
		//$date_end1 = date('Y-m-d 00:00:00', time());
		
		// LVM
		/*if ( isset($_POST['show_stats']) && !empty($_POST['show_stats']) )
		{
			$date_start = $_POST['date_stats_start'];
			$date_end = $_POST['date_stats_end'];
		}
		*/
		
		if ( isset($_POST['show_stats2']) && !empty($_POST['show_stats2']) )
		{
			$date_start2 = $_POST['date_stats_start2'];
			$date_end2 = $_POST['date_stats_end2'];
		}
		else
		{
			$date_start2 = date('Y-m-d H:i:s', time() - ( 24 * 60 * 60 * 365 ) );
			$date_end2 = date('Y-m-d 00:00:00', time());
		}
			
		// Recherche fiche	
		$conditions['date_start'] = array('column' => 'date', 'value' => $date_start2, 'operator' => '>=');
		$conditions['date_end'] = array('column' => 'date', 'value' => $date_end2, 'operator' => '<=');
		
		$fiches = Fiche::findFicheBy($conditions, -1, -1, 'date', true, false);
		
		// Recherche compte client	
		$conditions['date_start'] = array('column' => 'date_start', 'value' => $date_start2, 'operator' => '>=');
		$conditions['date_end'] = array('column' => 'date_start', 'value' => $date_end2, 'operator' => '<=');
		
		$accounts = FicheAbo::findAboBy($conditions, -1, -1, 'date_start', true);
		

		// LVM : recherche des comptes clients vraiments actifs avec une date de création dans la période considérée par mois
		//       Un 'compte actif' est actif avec au moins 1 modèle privé ou au moins 1 fiche privé
		if ( isset($_POST['show_stats1']) && !empty($_POST['show_stats1']) )
		{
			$date_start1 = $_POST['date_stats_start1'];
			$date_end1 = $_POST['date_stats_end1'];
		}
		else
		{
			$date_start1 = date('Y-m-d H:i:s', time() - ( 24 * 60 * 60 * 365 ) );
			$date_end1 = date('Y-m-d 00:00:00', time());
		}
		
		$conditions['date_start'] = array('column' => 'date_start', 'value' => $date_start1, 'operator' => '>=');
		$conditions['date_end'] = array('column' => 'date_start', 'value' => $date_end1, 'operator' => '<=');
		
		$accounts_activ = FicheAbo::findAboActiv();
		
		// LVM : rechercher les modèles publics (tous users)
		$conditions['date_start'] = array('column' => 'date', 'value' => $date_start2, 'operator' => '>=');
		$conditions['date_end'] = array('column' => 'date', 'value' => $date_end2, 'operator' => '<=');
		
		$conditions['public'] = 0;
		$conditions['active'] = 1;
		
		$publicmodels_activ = Fiche::findFicheBy($conditions, -1, -1, 'date', true, false);
		//
		
		// LVM
		$results['accounts_activ'] = $accounts_activ;
		$results['publicmodels_activ'] = $publicmodels_activ;
			
		$results['accounts'] = $accounts;
		$results['fiches'] = $fiches;
		
		// LVM
		//$results['date_start'] = $date_start;
		//$results['date_end'] = $date_end;
		
		$results['date_start1'] = $date_start1;
		$results['date_end1'] = $date_end1;
		
		$results['date_start2'] = $date_start2;
		$results['date_end2'] = $date_end2;
		
		return $results;
	}
	
	
	public function __construct() 
	{
		parent::__construct();
		
		$modulator = 1024 * 1024;
		$link = new Link();
		
		$result = $this->searchUserBy();
		
		$this->addTheme();
		$this->killTheme();
		$this->addProp();
		$this->killProp();
		$this->connectAsUser();
		$this->createUser();
		$this->saveConfig();
		$this->saveAbo($modulator);
		$this->storeSizeAllSubmit($modulator);
	
		
		$ficheLink = $link->getAdminLink('AdminFiche', true);
		$customersLink = $link->getAdminLink('AdminCustomers', true);
		$linkModule = $link->getModuleLink('fichevitrine', 'default');
		
		$autoSaveTime 		= Configuration::get('fichevitrine_autoSaveTime_');
		$autoSave 			= Configuration::get('fichevitrine_autoSave_');
		$fontList 			= Configuration::get('fichevitrine_fontList_');
		$startSize 			= Configuration::get('fichevitrine_fontSizeStart_');
		$endSize 			= Configuration::get('fichevitrine_fontSizeEnd_');
		$jsDir				= _MODULE_DIR_.'fichevitrine/js/';
		
		
		$conditions = array();
		
		// LVM
		$conditions2 = array();
		
		// LVM : Recherche dans la table des user abonnés LFV
		if ( isset($_POST['f_searchAccount']) )
		{	
			// LVM	
			$f_accountSurname = isset($_POST['f_accountSurname'])?$_POST['f_accountSurname']:''; 
			
			if ( isset($_POST['f_accountSurname']) && !empty($_POST['f_accountSurname']) ) 
			{
				// LVM : il manque la value et inversion avec le nom de la colonne...
				//$conditions["customer_lastname"] = array("operator" => "LIKE", "column" => $_POST['f_accountSurname']);
				$conditions["customer_lastname"] = array("column" => 'customer_lastname', "operator" => "LIKE", "value" => $_POST['f_accountSurname']);
			}
			
			// LVM	
			$f_accountName = isset($_POST['f_accountName'])?$_POST['f_accountName']:''; 
				
			if ( isset($_POST['f_accountName'])  && !empty($_POST['f_accountName']) ) 
			{
				// LVM : il manque la value et inversion avec le nom de la colonne...
				//$conditions["customer_firstname"] = $_POST['f_accountName'];
				//$conditions["customer_firstname"] = array("operator"=>"LIKE", "column"=>$_POST['customer_firstname']);	
				$conditions["customer_firstname"] = array("column" => 'customer_firstname', "operator" => "LIKE", "value" => $_POST['f_accountName']);
			}
			
			// LVM	
			$f_accountMail = isset($_POST['f_accountMail'])?$_POST['f_accountMail']:''; 
			
			if ( isset($_POST['f_accountMail'])  && !empty($_POST['f_accountMail']) ) 
			{
				// LVM : il manque la value et inversion avec le nom de la colonne...
				//$conditions["customer_email"] = $_POST['f_accountMail'];	
				//$conditions["customer_email"] = array("operator"=>"LIKE", "column"=>$_POST['customer_email']);
				$conditions["customer_email"] = array("column" => 'customer_email', "operator" => "LIKE", "value" => $_POST['f_accountMail']);
			}	
			
			// LVM	
			$f_accountCompany = isset($_POST['f_accountCompany'])?$_POST['f_accountCompany']:''; 
			
			// LVM : Il faut requêter sur une table Prestashop (ps_Customer) et faire une jointure avec la table ps_Abo...
			//       et pas simplement sur ps_ficheAbo à moins de rajouter un champ dans la table...
			if ( isset($_POST['f_accountCompany'])  && !empty($_POST['f_accountCompany']) ) 
			{
				$conditions2["customer_company"] = array("column" => 'company', "operator" => "LIKE", "value" => $_POST['f_accountCompany']);
			}	
		}
		else
		{
			$f_accountSurname = '';
			$f_accountName = '';
			$f_accountMail = '';
			$f_accountCompany = '';
		}
		
		// LVM
		//$resultsPerPage 	= 15;
		$resultsPerPage 	= 50;
		
		// LVM : pb car conditions2 pas utilisé... et pb car on ne peut utiliser la taille de findAboBy
		//       car besoin de start et end...
		//$numPages = ceil( FicheAbo::getTotalAboWhere($conditions) / $resultsPerPage ) - 1;
		$numPages = ceil( FicheAbo::getTotalAboWhere($conditions, $conditions2) / $resultsPerPage ) - 1;
		
		$currentPage = (isset($_GET['page'])) ? (int)($_GET['page']) : 0;
		$currentPage = ( $currentPage > $numPages ) ? $numPages : $currentPage;
		$currentPage = ( $currentPage < 0 ) ? 0 : $currentPage;
		
		$start = $currentPage * $resultsPerPage;
		$end = $resultsPerPage;
		
		// LVM : trier par ordre descendant au lieu d'ascendant et par date start et pas id
		//$aboList 			= FicheAbo::findAboBy($conditions, $start, $end);
		
		// LVM : Il faut requêter sur une table Prestashop (ps_Customer) et faire une jointure avec la table ps_Abo...
		//       et pas simplement sur ps_ficheAbo à moins de rajouter un champ dans la table...
		//$aboList 			= FicheAbo::findAboBy($conditions, $start, $end, 'date_start', false);
		$aboList 			= FicheAbo::findAboBy($conditions, $start, $end, 'date_start', false, $conditions2);
		
		/*
		echo 'avant1 dump aboList'.'---';
		var_dump($aboList);
		echo 'apres1 dump aboList'.'---';
		*/
		
		foreach ($aboList as $abo)
		{
			$abo->storeSize /= $modulator;
			
			/*
			echo 'avant5 dump obj abo'.'---';
			var_dump($abo);
			echo 'apres5 dump obj abo'.'---';
			*/
			
			// LVM : ajouter l'attribut company pour ne pas que le tpl plante 	
			//       mais en fait plus nécessaire après les ajouts requête sql...		
			/*
			if (property_exists($abo, 'company'))
			{ 
				// rien
				//echo 'company2 = '.$abo->company.'---';
			}
			else
			{
				$abo->company = '';
			}
			*/
		}
		
		/*
		echo 'avant2 dump aboList'.'---';
		var_dump($aboList);
		*/
		
		$stats = $this->getStats();
		
		
		$this->context->smarty->assign(array(
			'props' => FicheProp::findAll(),
			'themes' => FicheTheme::findAll(),
			
			// LVM
			//'date_stats_start' => $stats['date_start'],
			//'date_stats_end' => $stats['date_end'],
			'date_stats_start2' => $stats['date_start2'],
			'date_stats_end2' => $stats['date_end2'],
			
			'statsFiches' => json_encode($stats['fiches']),
			'statsAccounts' => json_encode($stats['accounts']),
			
			// LVM : comptes créés actifs (au moins 1 modèle et au moins 1 fiche)
			'statsAccounts_activ' => json_encode($stats['accounts_activ']),
			
			// Public modèle activ
			'statsPublicModels_activ' => json_encode($stats['publicmodels_activ']),
			
			'date_stats_start1' => $stats['date_start1'],
			'date_stats_end1' => $stats['date_end1'],
			//
			
			'ficheLink' => $ficheLink,
			
			'customersLink' => $customersLink,
			'jsDir' => $jsDir,
			'aboList' => $aboList,
			'currentPage' => $currentPage,
			'numPagesAbo' => $numPages,
			'autoSave' => $autoSave,
			'autoSaveTime' => $autoSaveTime,
			'linkModule' => $linkModule,
			'fontList' => $fontList,
			'startSize' => $startSize,
			'result' => $result,
			'endSize' => $endSize
			
			// LVM
			, 'currentSurname' => $f_accountSurname
			, 'currentName' => $f_accountName
			, 'currentMail' => $f_accountMail
			, 'currentCompany' => $f_accountCompany
		));
		
		$this->setTemplate('adminfiche.tpl');
	}
	

	//override this stupid behavior of prestashop...
	public function createTemplate($tpl_name)
    {
		$path = _PS_MODULE_DIR_.$this->module->name.'/views/templates/admin/';
		$tpl = $path.$tpl_name;
        
        if (file_exists($tpl) && $this->viewAccess())
            return $this->context->smarty->createTemplate($tpl, $this->context->smarty);

        return parent::createTemplate($tpl_name);
    }
	
}
